<?php
/**
 * Aihcontacts Controller
 *
 * PHP version 5
 *
 * @category Controller
 * @package  Croogo
 * @version  1.0
 * @author   Tran Van Dung <dungtv@ic-t.info>
 * @license  http://www.opensource.org/licenses/mit-license.php The MIT License
 * @link     http://www.croogo.org
 */
class AihcontactsController extends AppController {
/**
 * Controller name
 *
 * @var string
 * @access public
 */
    public $name = 'Aihcontacts';
/**
 * Models used by the Controller
 *
 * @var array
 * @access public
 */
    public $uses = array('Aihcontact', 'Contacttype', 'Bank', 'Country');
/**
 * Helpers used by the Controller
 *
 * @var array
 * @access public
 */
    public $helpers = array('Text', 'Html', 'Js');

    protected $paginate = array(
        'limit' => 10,
        );

/**
 * Before executing controller actions
 *
 * @return void
 * @access public
 */
    public function beforeFilter() {
        parent::beforeFilter();
        
        if ($this->action == 'add' || $this->action == 'edit' || $this->action == 'admin_add' || $this->action == 'admin_edit') {
            $this->Security->validatePost = false;
        }
//        $this->Aihcontact->unbindModel(array('hasAndBelongsToMany' => array('Bank')));
    }

/**
 * Admin index
 *
 * @return void
 * @access public
 */
    public function admin_index() {
        $this->set('title_for_layout', __('CONTACT LIST'));

        $this->Session->delete('cur_bank1s');
        $this->Session->delete('cur_bank2s');
        $this->Session->delete('cur_contacttype');
        
        $windowMsg = false;
        if($this->params['action']=='admin_browse') {
            $windowMsg = true;
            $scriptWindowMsg = $this->windowMsg();
            $this->set('scriptWindowMsg', $scriptWindowMsg);
            $contacttype = 1;
            if(isset($this->params['named']['contacttype']) && $this->params['named']['contacttype'] > 0 && $this->params['named']['contacttype'] < 5) {
                $contacttype = $this->params['named']['contacttype'];
            }
            $this->paginate['Aihcontact']['conditions'] = array('Aihcontact.contacttype_id' => $contacttype);
            $this->set('contacttype', $contacttype);
            
            $newest = $this->Aihcontact->find('first', array('fields' => array('Aihcontact.id', 'Aihcontact.name'), 'conditions' => array('Aihcontact.contacttype_id' => $contacttype), 'order' => array('Aihcontact.id DESC')));
            $this->set('newest', $newest);
        }
        $this->set('windowMsg', $windowMsg);
        
        $this->Aihcontact->recursive = 0;
        $this->paginate['Aihcontact']['order'] = 'Aihcontact.created DESC';
        $this->set('aihcontacts', $this->paginate());
    }
/*
    public function windowMsg2() {
        $output = "
                $(function(){
                    // don't forget this init!      
                    $.initWindowMsg();

                    var childWin;
                    $('.openWin').click(function(){
                        var bank = $(this).attr('rel');
                        bank = (bank == 2) ? '/bank:2' : '';
                        childWin = window.open('".Router::url('/admin/banks/browse', true)."'+bank, 'child', 'modal,width=1024,height=768,scrollbars=yes');
                        if (window.focus) {childWin.focus()}
                    });

                    // set up the message handlers, listen for events 'childMsg1' and 'childMsg2'     
                    $.windowMsg('childMsg1', function(message) {
                        var temp = message.split(':::');
                        $('#b1_id_id').val(temp[0]);
                        $('#b1_name_id').val(temp[1]);
                        $('#b1_address_id').val(temp[2]);
                        $('#b1_account_id').val(temp[3]);
                        $('#b1_swift_code_id').val(temp[4]);
                    });

                    $.windowMsg('childMsg2', function(message) {
                        
                        var temp = message.split(':::');
                        $('#b2_id_id').val(temp[0]);
                        $('#b2_name_id').val(temp[1]);
                        $('#b2_address_id').val(temp[2]);
                        $('#b2_account_id').val(temp[3]);
                        $('#b2_swift_code_id').val(temp[4]);
                    });
                });";

        return $output;
    }
*/
/**
 * Admin add
 *
 * @return void
 * @access public
 */
    public function admin_add() {
        $this->set('title_for_layout', __('CONTACT DETAIL'));

        $redirect = array('action'=>'index');
        $rel = '';
        $contacttype = 1;
        if(isset($this->params['named']['rel']) && $this->params['named']['rel']=='browse') {
            $rel = 'browse';
            if(isset($this->params['named']['contacttype']) && $this->params['named']['contacttype'] > 0 && $this->params['named']['contacttype'] < 5) {
                $contacttype = $this->params['named']['contacttype'];
            }
            $redirect = array('action'=>'browse', 'contacttype' => $contacttype);
        }
        if (!empty($this->request->data)) {
            $country = $this->Country->find('first', array('conditions' => array('name' => $this->request->data['Aihcontact']['country'])));
            if(!$country) {
                $country = array('name' => $this->request->data['Aihcontact']['country']);
                $this->Country->save($country);
            }
            
            $this->request->data['Aihcontact']['contacttype_id'] = $this->request->data['Contacttype']['Contacttype'];
            unset($this->request->data['Contacttype']);
            
            $bank1Ids = array();
            $bank2Ids = array();
            $bank1 = false;
            $bank2 = false;
            if(isset($this->request->data['Bank'])) {
                foreach ($this->request->data['Bank'] as $bank) {
                    if($bank['t_bank']==1) {
                        $bank1 = true;
                        $bank1Ids[] = $bank['id'];
                    } elseif($bank['t_bank']==2) {
                        $bank2 = true;
                        $bank2Ids[] = $bank['id'];
                    }
                }
            }
            if(true) {
                unset($this->request->data['Bank']);
                $this->request->data['Aihcontact']['bank1'] = $this->Aihcontact->encodeData($bank1Ids);
                $this->request->data['Aihcontact']['bank2'] = $this->Aihcontact->encodeData($bank2Ids);
                $this->request->data['Aihcontact']['address'] = nl2br($this->request->data['Aihcontact']['address']);
                $this->Aihcontact->create();
                if ($this->Aihcontact->save($this->request->data)) {
                    $this->Aihcontact->lock($bank1Ids);
                    $this->Aihcontact->lock($bank2Ids);
                    $this->Aihcontact->lock(array($this->request->data['Aihcontact']['contacttype_id']), 'cc_contacttypes');
                    //$this->Session->setFlash(__('The Contact has been saved'), 'default', array('class' => 'success'));

                    $this->redirect($redirect);
                } else {
                    $contacttypes = $this->Aihcontact->Contacttype->find('list', array('order' => array('Contacttype.name ASC')));
                    $this->set(compact('contacttypes'));
                    $bank1s = $this->Bank->find('list');
                    $bank2s = $bank1s;
                    $this->set(compact('bank1s'));
                    $this->set(compact('bank2s'));
                    $this->set('rel', $rel);
                    $this->set('contacttype', $contacttype);
                    $this->Session->setFlash(__('The Contact could not be saved. Please, try again.'), 'default', array('class' => 'error'));
                } 
            } else {
                $this->Session->setFlash(__('The Contact could not be saved, at least two or more Bank in Contact. Please, try again.'), 'default', array('class' => 'error'));
            }
        } 
        $auto_complete = $this->jquery_auto_complete();
        $this->set('auto_complete', $auto_complete);
//        $scriptWindowMsg = $this->windowMsg();
//        $this->set('scriptWindowMsg', $scriptWindowMsg);
        $contacttypes = $this->Aihcontact->Contacttype->find('list', array('order' => array('Contacttype.name ASC')));
        $this->set(compact('contacttypes'));
        $bank1s = $this->Bank->find('list');
        $bank2s = $bank1s;
        $this->set(compact('bank1s'));
        $this->set(compact('bank2s'));
        $this->set('rel', $rel);
        $this->set('contacttype', $contacttype);
    }
    
    public function jquery_auto_complete() {
        $countries = $this->Country->find('list', array('fields' => 'name'));
        $output = '
            $(function() {
                var availableCountries = ["'.implode('","', $countries).'"];
                $( "#AihcontactCountry" ).autocomplete({
                    source: availableCountries
                });
            });';
		return $output;
    }

    public function admin_add_bank1($id=null){
        $bank1s = $this->Bank->find('first', array('conditions' => array('Bank.id' => $id)));
        $this->set('bank1s', $bank1s);
        $this->layout = 'ajax';
    }
    
    public function admin_add_bank2($id=null){
        $bank2s = $this->Bank->find('first', array('conditions' => array('Bank.id' => $id)));
        $this->set('bank2s', $bank2s);
        $this->layout = 'ajax';
    }
    
    public function admin_delete_bank($id=null){
        $this->layout = 'ajax';
        $success = false;
        if($id != '') {
            $success = true;
        }
        $success = $this->Aihcontact->encodeData(array('success' => $success), array('json' => true, 'trim' => false));
        $this->set('success', $success);
    }
    
/**
 * Admin edit
 *
 * @param int $id 
 * @return void
 * @access public
 */
    public function admin_edit($id = null) {
        if($id==100) {
            $this->set('title_for_layout', __('AIH CONTACT DETAIL'));
        } else {
            $this->set('title_for_layout', __('CONTACT DETAIL'));
        }
        $this->set('id', $id);

        $redirect = array('action'=>'index');
        $rel = '';
        $contacttype = 1;
        if(isset($this->params['named']['rel']) && $this->params['named']['rel']=='browse') {
            $rel = 'browse';
            if(isset($this->params['named']['contacttype']) && $this->params['named']['contacttype'] > 0 && $this->params['named']['contacttype'] < 5) {
                $contacttype = $this->params['named']['contacttype'];
            }
            $redirect = array('action'=>'browse', 'contacttype' => $contacttype);
        }
        $this->set('rel', $rel);
        
        if (!$id && empty($this->request->data)) {
            $this->Session->setFlash(__('Invalid Contact'), 'default', array('class' => 'error'));
            $this->redirect($redirect);
        }
        if (!empty($this->request->data)) {
            $country = $this->Country->find('first', array('conditions' => array('name' => $this->request->data['Aihcontact']['country'])));
            if(!$country) {
                $country = array('name' => $this->request->data['Aihcontact']['country']);
                $this->Country->save($country);
            }
            
            $this->request->data['Aihcontact']['contacttype_id'] = $this->request->data['Contacttype']['Contacttype'];
            unset($this->request->data['Contacttype']);
            
            $bank1Ids = array();
            $bank2Ids = array();
            $bank1 = false;
            $bank2 = false;
            if(isset($this->request->data['Bank'])) {
                foreach ($this->request->data['Bank'] as $bank) {
                    if($bank['t_bank']==1) {
                        $bank1 = true;
                        $bank1Ids[] = $bank['id'];
                    } elseif($bank['t_bank']==2) {
                        $bank2 = true;
                        $bank2Ids[] = $bank['id'];
                    }
                }
            }
            if(true) {
                unset($this->request->data['Bank']);
                $this->request->data['Aihcontact']['bank1'] = $this->Aihcontact->encodeData($bank1Ids);
                $this->request->data['Aihcontact']['bank2'] = $this->Aihcontact->encodeData($bank2Ids);
                $this->request->data['Aihcontact']['address'] = nl2br($this->request->data['Aihcontact']['address']);
                if ($this->Aihcontact->save($this->request->data)) {

                    $cur_bank1Ids = $this->Session->read('cur_bank1s');
                    $cur_bank2Ids = $this->Session->read('cur_bank2s');
                    $cur_contacttype = $this->Session->read('cur_contacttype');

                    $this->Aihcontact->lock($cur_bank1Ids, 'cc_banks', -1);
                    $this->Aihcontact->lock($cur_bank2Ids, 'cc_banks', -1);
                    $this->Aihcontact->lock(array($cur_contacttype), 'cc_contacttypes', -1);

                    $this->Aihcontact->lock($bank1Ids);
                    $this->Aihcontact->lock($bank2Ids);
                    $this->Aihcontact->lock(array($this->request->data['Aihcontact']['contacttype_id']), 'cc_contacttypes');
                    //$this->Session->setFlash(__('The Contact has been updated'), 'default', array('class' => 'success'));

                    $this->redirect($redirect);
                } else {
                    $this->request->data = $this->Aihcontact->read(null, $id);
                    $bank1Ids = $this->Aihcontact->decodeData($this->request->data['Aihcontact']['bank1']);
                    $bank2Ids = $this->Aihcontact->decodeData($this->request->data['Aihcontact']['bank2']);

                    $bank1s = $this->Bank->find('list', array('conditions' => array('NOT' => array('Bank.id' => $bank1Ids))));
                    $bank2s = $this->Bank->find('list', array('conditions' => array('NOT' => array('Bank.id' => $bank2Ids))));
                    $this->set(compact('bank1s'));
                    $this->set(compact('bank2s'));

                    $cur_bank1s = $this->Bank->find('all', array('conditions' => array('Bank.id' => $bank1Ids)));
                    $cur_bank2s = $this->Bank->find('all', array('conditions' => array('Bank.id' => $bank2Ids)));
                    $this->set('cur_bank1s', $cur_bank1s);
                    $this->set('cur_bank2s', $cur_bank2s);
//                        $scriptWindowMsg = $this->windowMsg();
//                        $this->set('scriptWindowMsg', $scriptWindowMsg);
                    $contacttypes = $this->Aihcontact->Contacttype->find('list',array('order' => array('Contacttype.name ASC')));
                    $this->set(compact('contacttypes'));
                    $this->set('contacttype', $contacttype);
                    $this->Session->setFlash(__('The Contact could not be updated. Please, try again.'), 'default', array('class' => 'error'));
                } 
            } else {
                $this->Session->setFlash(__('The Contact could not be updated, at least two or more Bank in Contact. Please, try again.'), 'default', array('class' => 'error'));
            }
        }
        if (empty($this->request->data)) {
            $this->request->data = $this->Aihcontact->read(null, $id);
            $bank1Ids = $this->Aihcontact->decodeData($this->request->data['Aihcontact']['bank1']);
            $bank2Ids = $this->Aihcontact->decodeData($this->request->data['Aihcontact']['bank2']);
            
            $this->Session->write('cur_bank1s', $bank1Ids);
            $this->Session->write('cur_bank2s', $bank2Ids);
            $this->Session->write('cur_contacttype', $this->request->data['Aihcontact']['contacttype_id']);
            
            $bank1s = $this->Bank->find('list', array('conditions' => array('NOT' => array('Bank.id' => $bank1Ids))));
            $bank2s = $this->Bank->find('list', array('conditions' => array('NOT' => array('Bank.id' => $bank2Ids))));
            $this->set(compact('bank1s'));
            $this->set(compact('bank2s'));
            
            $cur_bank1s = $this->Bank->find('all', array('conditions' => array('Bank.id' => $bank1Ids)));
            $cur_bank2s = $this->Bank->find('all', array('conditions' => array('Bank.id' => $bank2Ids)));
            $this->set('cur_bank1s', $cur_bank1s);
            $this->set('cur_bank2s', $cur_bank2s);
//            $scriptWindowMsg = $this->windowMsg();
//            $this->set('scriptWindowMsg', $scriptWindowMsg);
            if($id==100) {
                $contacttypes = array('0' => 'AIH');
            } else {
                $contacttypes = $this->Aihcontact->Contacttype->find('list',array('order' => array('Contacttype.name ASC')));
            }
            $this->set(compact('contacttypes'));
//            $this->set('contacttype', $contacttype);
            $auto_complete = $this->jquery_auto_complete();
            $this->set('auto_complete', $auto_complete);
        }
    }

/**
 * Admin delete
 *
 * @param int $id 
 * @return void
 * @access public
 */
    public function admin_delete($id = null) {
        if (!$id) {
            $this->Session->setFlash(__('Invalid id for Contact'), 'default', array('class' => 'error'));
            $this->redirect(array('action'=>'index'));
        }

        $aihcontact = $this->Aihcontact->find('first', array(
            'conditions' => array(
                'Aihcontact.id' => $id,
            ),
        ));
        if (isset($aihcontact['Aihcontact'])) {
            if($aihcontact['Aihcontact']['lock']<=0) {
                if ($this->Aihcontact->delete($id)) {
                    $this->Aihcontact->lock($this->Aihcontact->decodeData($aihcontact['Aihcontact']['bank1']), 'cc_banks', -1);
                    $this->Aihcontact->lock($this->Aihcontact->decodeData($aihcontact['Aihcontact']['bank2']), 'cc_banks', -1);
                    $this->Aihcontact->lock(array($aihcontact['Aihcontact']['contacttype_id']), 'cc_contacttypes', -1);
                    //$this->Session->setFlash(__('Contact deleted'), 'default', array('class' => 'success'));
                    $this->redirect(array('action'=>'index'));
                }
            } else {
                $this->Session->setFlash(__('Contact was locked'), 'default', array('class' => 'success'));
                $this->redirect(array('action'=>'index'));
            }
        } else {
            $this->Session->setFlash(__('Invalid id for Contact'), 'default', array('class' => 'error'));
            $this->redirect(array('action'=>'index'));
        }
    }

    public function windowMsg() {
        $output = "
                $(function(){
                    // don't forget this init!      
                    $.initWindowMsg();

                    // upon click of a button, send corresponding text input value to parent window
                    $('.childButton').click(function(){
                        var contacttype = $(this).attr('rel');
                        if(contacttype < 1 && contacttype > 5){
                            contacttype = 1;
                        }
                        var childMsg = 'childMsg' + contacttype
                        var value = $(this).attr('title');
                        $.triggerParentEvent(childMsg, value); 
                        window.close();
                    });
                    
                    // auto add marker
                    var newest = $('#newest').val();
                    $.triggerParentEvent('childMsg', newest); 
                    window.close();
                });";

        return $output;
    }

    public function admin_browse() {
        $this->layout = 'admin_full';
        $this->admin_index();
    }

}
?>